import json
import unittest

from app import create_app, db


class MainTest(unittest.TestCase):

    def setUp(self):
        self.app = create_app('test')
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client(use_cookies=False)
        db.drop_all()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()  # 放到最后一行执行

    def test_register(self):
        post_data = {'name': 'linyuelin',
                     'password': 'admin123',
                     'password2': "admin123",
                     'email': ''
                     }
        resp = self.client.post('/user/register', json=post_data, content_type="application/json")
        result = resp.get_json()
        print(result)
        self.assertEqual(result['code'], 0)

    def test_login_none_name_or_psw(self):
        post_data = {'name': 'linyuelin', 'password': ''}
        resp = self.client.post('/user/login', json=post_data, content_type="application/json")
        result = resp.get_json()
        self.assertEqual(result['code'], 400)
        self.assertIn(result['info'], '参数不全')

    def test_login_wrong_name_or_psw(self):
        post_data = {'name': 'linyuelin', 'password': 'admin'}
        resp = self.client.post('user/login', json=post_data)
        result = resp.get_json()
        self.assertIn(result['info'], "用户不存在")

    def test_logout(self):
        resp = self.client.get("/user/logout", content_type='application/json')
        # data = resp.get_data(as_text=True)
        data = resp.get_json()
        self.assertEqual(data['code'], 400)


if __name__ == '__main__':
    unittest.main()
    # MainTest.test_login_none_name_or_psw().runTest()
